package com.ndood.agent.service.system.impl;

import java.util.Date;
import java.util.List;

import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.ndood.agent.dao.system.StaffDao;
import com.ndood.agent.dao.system.StaffRoleDao;
import com.ndood.agent.dao.system.extend.ExtendStaffDao;
import com.ndood.agent.pojo.comm.dto.DataTableDto;
import com.ndood.agent.pojo.system.StaffPo;
import com.ndood.agent.pojo.system.StaffRolePo;
import com.ndood.agent.pojo.system.StaffRoleQuery;
import com.ndood.agent.pojo.system.dto.RoleDto;
import com.ndood.agent.pojo.system.dto.StaffDto;
import com.ndood.agent.pojo.system.query.StaffQo;
import com.ndood.agent.service.system.SystemStaffService;

/**
 * 用户模块业务类
 * @author ndood
 */
@Service
public class SystemStaffServiceImpl implements SystemStaffService{
	
	@Autowired
	private StaffDao staffDao;
	
	@Autowired
	private StaffRoleDao staffRoleDao;
	
	@Autowired
	private ExtendStaffDao extendStaffDao;
	
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	@Override
	public String addStaff(StaffDto dto) throws Exception {
		// Step1: 补充相关默认字段
		dto.setCreateTime(new Date());
		dto.setUpdateTime(new Date());
		if(dto.getPassword()==null) {
			dto.setPassword(passwordEncoder.encode("123456"));
		}else {
			dto.setPassword(passwordEncoder.encode(dto.getPassword()));
		}
		if(dto.getTradePassword()==null) {
			dto.setTradePassword(passwordEncoder.encode("123456"));
		}else {
			dto.setTradePassword(passwordEncoder.encode(dto.getTradePassword()));
		}

		// Step2: 保存用户信息
		StaffPo po = new StaffPo();
		po.setAgentId(dto.getAgentId());
		po.setCreateTime(dto.getCreateTime());
		po.setEmail(dto.getEmail());
		po.setEmailNonceStr(dto.getEmailNonceStr());
		po.setEmailStatus(dto.getEmailStatus());
		po.setHeadImgUrl(dto.getHeadImgUrl());
		po.setLastLoginIp(dto.getLastLoginIp());
		po.setLastLoginTime(dto.getLastLoginTime());
		po.setMobile(dto.getMobile());
		po.setNickName(dto.getNickName());
		po.setPassword(dto.getPassword());
		po.setSocialUserId(dto.getSocialUserId());
		po.setStatus(dto.getStatus());
		po.setTradePassword(dto.getTradePassword());
		po.setUpdateTime(dto.getUpdateTime());
		
		staffDao.insertSelective(po);
		
		// 添加用户角色关联表
		if(dto.getRoleIds()!=null) {
			for (Integer roleId : dto.getRoleIds()) {
				StaffRolePo srPo = new StaffRolePo();
				srPo.setUserId(po.getId());
				srPo.setRoleId(roleId);
				// 添加用户角色关系表
				staffRoleDao.insertSelective(srPo);
			}
		}
		
		return String.valueOf(po.getId());
	}

	@Override
	public void batchDeleteStaff(Integer[] ids) {
		// staffDao.deleteByIdByIds(Arrays.asList(ids));
		for (Integer id : ids) {
			staffDao.deleteByPrimaryKey(id);
			StaffRoleQuery example = new StaffRoleQuery();
			example.createCriteria().andUserIdEqualTo(id);
			staffRoleDao.deleteByExample(example);
		}
	}

	@Override
	public void updateStaff(StaffDto dto) throws Exception {
		// Step1: 判断是否更新密码
		StaffPo po = staffDao.selectByPrimaryKey(dto.getId());
		String newPassword = dto.getPassword();
		if(!StringUtils.isEmpty(newPassword)){
			if(!passwordEncoder.matches(po.getPassword(), newPassword)){
				dto.setPassword(passwordEncoder.encode(newPassword));
			}
		}
		String newTradePassword = dto.getTradePassword();
		if(!StringUtils.isEmpty(newTradePassword)){
			if(!passwordEncoder.matches(po.getTradePassword(), newTradePassword)){
				dto.setTradePassword(passwordEncoder.encode(newTradePassword));
			}
		}
		dto.setUpdateTime(new Date());
		
		po.setAgentId(dto.getAgentId());
		po.setCreateTime(dto.getCreateTime());
		po.setEmail(dto.getEmail());
		po.setEmailNonceStr(dto.getEmailNonceStr());
		po.setEmailStatus(dto.getEmailStatus());
		po.setHeadImgUrl(dto.getHeadImgUrl());
		po.setLastLoginIp(dto.getLastLoginIp());
		po.setLastLoginTime(dto.getLastLoginTime());
		po.setMobile(dto.getMobile());
		po.setNickName(dto.getNickName());
		po.setPassword(dto.getPassword());
		po.setSocialUserId(dto.getSocialUserId());
		po.setStatus(dto.getStatus());
		po.setTradePassword(dto.getTradePassword());
		po.setUpdateTime(dto.getUpdateTime());
		
		// Step2: 更新时间
		staffDao.updateByPrimaryKeySelective(po);
		
		StaffRoleQuery srExample = new StaffRoleQuery();
		srExample.createCriteria().andUserIdEqualTo(dto.getId());
		staffRoleDao.deleteByExample(srExample);
		
		if(dto.getRoleIds()!=null) {
			for (Integer roleId : dto.getRoleIds()) {
				StaffRolePo srPo = new StaffRolePo();
				srPo.setUserId(po.getId());
				srPo.setRoleId(roleId);
				// 添加用户角色关系表
				staffRoleDao.insertSelective(srPo);
			}
		}
		
	}
	
	@Override
	public StaffDto getStaff(Integer id) throws Exception {
		// Step1: 获取用户信息时不能暴露密码
		StaffDto dto = extendStaffDao.extendFindById(id);
		dto.setPassword(null);
		if(dto.getRoles()!=null) {
			List<Integer> roleIds = Lists.newArrayList();
			for (RoleDto role : dto.getRoles()) {
				roleIds.add(role.getId());
			}
		}
		return dto;
	}

	/**
	 * 分页查询用户信息，采用jpa的dto形式
	 */
	public DataTableDto pageStaffList(StaffQo query) throws Exception{
		Page<StaffDto> page = extendStaffDao.extendFindByStaffQo(query);
		return new DataTableDto(page.getContent(), page.getTotalElements());
	}

}